<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
require_once( JApplicationHelper::getPath( 'admin_html' ) );
JTable::addIncludePath( JPATH_COMPONENT.DS.'tables' );

switch( $task )
{
	case 'edit':
	case 'add':
		editNews( $option );
		break;
	case 'apply':
	case 'save':
		saveNews( $option, $task );
		break;
	case 'remove':
		removeNews( $option );
		break;
	default:
		showNews( $option );
		break;
}

function editNews( $option )
{
	$row =& JTable::getInstance( 'BPNews', 'Table' );
	$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
	$id = $cid[0];
	$row->load( $id );
	$lists = array();
	$lists['published'] = JHTML::_('select.booleanlist', 'published', 'class="inputbox"', $row->published );
	HTML_bpnews::editNews( $row, $lists, $option );
}

function removeNews( $option )
{
	global $mainframe;
	$cid = JRequest::getVar( 'cid', array(), '', 'array' );
	$db =& JFactory::getDBO();
	if( count( $cid ) )
	{
		$cids = implode( ',', $cid );
		$query = "DELETE FROM #__bpnews WHERE id IN ( $cids )";
		$db->setQuery( $query );
		if( !$db->query() )
		{
			echo "<script> alert('".$db->getErrorMsg()."');
			window.history.go(-1); </script>\n";
		}
		
		$mainframe->redirect( 'index.php?option=' . $option, "New Item deleted." );
	}
}

function saveNews( $option, $task )
{
	global $mainframe;
	$row =& JTable::getInstance( 'BPNews', 'Table' );
	
	if( !$row->bind( JRequest::get( 'post' ) ) )
	{
		echo "<script> alert('".$row->getError()."');
			  window.history.go(-1); </script>\n";
		exit();
	}
	
	$row->text = JRequest::getVar( 'text', '', 'post', 'string', JREQUEST_ALLOWRAW );
	
	if( !$row->created )
		$row->created = date( 'Y-m-d H:i:s' );
	
	if( !$row->store() )
	{
		echo "<script> alert('".$row->getError()."');
			  window.history.go(-1); </script>\n";
		exit();
	}
	
	switch( $task )
	{
		case 'apply':
			$msg = 'Changes to News Item saved.';
			$link = 'index.php?option=' . $option . '&task=edit&cid[]=' . $row->id;
			break;
		case 'save':
		default:
			$msg = 'News Item saved';
			$link = 'index.php?option=' . $option;
			break;
	}
	
	$mainframe->redirect( $link, $msg );
	
}

function showNews( $option )
{
	$db =& JFactory::getDBO();
	$query = "SELECT * from #__bpnews";
	$db->setQuery( $query );
	$rows = $db->loadObjectList();
	if( $db->getErrorNum() )
	{
		echo $db->stderr();
		return false;
	}
	
	HTML_bpnews::showNews( $option, $rows );
}

?>